Skip to content

fix(#5791): REBUILD INDEX preserves an explicitly-named FULL_TEXT/GEOSPATIAL index - #5925

Merged
lvca merged 3 commits into
mainfrom
issue-5791-fulltext-build-existing
Aug 7, 2026
Merged

lvca merged 3 commits into
mainfrom
issue-5791-fulltext-build-existing

Conversation

@lvca

@lvca lvca commented Aug 7, 2026

Copy link
Copy Markdown
Member

Summary

Investigation of #5791 (a follow-up report to #4732) found three claimed symptoms; only one still reproduces on main.

  • Confirmed and fixed: REBUILD INDEX <name> silently renames an explicitly-named FULL_TEXT/GEOSPATIAL index back to its auto-derived typeName[properties] form. RebuildIndexStatement.buildIndex() drops and recreates the TypeIndex through a fresh TypeIndexBuilder but never calls withIndexName(...), so TypeIndexBuilder.create() never populates metadata.typeIndexName and LocalDocumentType.addIndexInternal falls back to the default name. A plain LSM_TREE rebuild happened to keep its name because its metadata object is reused as-is, but FULL_TEXT/GEOSPATIAL reconstruct their metadata from the index's persisted JSON to recover type-specific settings (analyzers, GeoHash precision), and typeIndexName isn't part of that JSON - so it silently reverts. Every name-based lookup breaks after the rebuild, including SEARCH_INDEX, which has no other way to reference an index. Fixed by passing withIndexName(idx.getName()) into the rebuild.

  • Does not reproduce on main: the core reported defect ("CREATE INDEX ... FULL_TEXT over pre-existing rows indexes nothing matchable") and the NPE on prefix queries. A stress test (FullTextBuildOverChurnedDataTest) replays the reporter's SCD2-style churn pattern - ~6,800 staggered inserts, several rounds of growing updates that force some records into placeholder relocation, and interleaved deletes, crossing the 5,000-record build-batch-commit boundary - then builds the FULL_TEXT index and checks every marked row is matchable, exercises the same REBUILD INDEX path, and runs a prefix query against the churned index. All pass cleanly. This is consistent with BUG: FULL_TEXT index (re)build over existing data is broken - CREATE INDEX on a populated type indexes nothing matchable, and REBUILD INDEX crashes and drops the index #4732's build-through-put() rewrite (already in 26.7.1+) and Index cursor follow-ups from #5601: LSMTreeIndexCursor.next() returns null after hasNext(), FetchFromIndexStep.reset() leaks its cursors #5635's IndexCursor contract change (next() never returns null, so the class of NPE reported can no longer occur) - neither of which the reporter had confirmed against main when filing.

Changes

  • engine/src/main/java/com/arcadedb/query/sql/parser/RebuildIndexStatement.java: preserve the index's name across REBUILD INDEX.
  • engine/src/test/java/com/arcadedb/index/RebuildIndexPreservesNameTest.java: regression test covering plain LSM_TREE, FULL_TEXT, and GEOSPATIAL named-index rebuilds.
  • engine/src/test/java/com/arcadedb/index/fulltext/FullTextBuildOverChurnedDataTest.java: reproduces the reporter's exact churn/build/rebuild/prefix-query scenario as a @Tag("slow") regression test.

Test plan

  • mvn -pl engine install -DskipTests compiles cleanly
  • New tests fail without the fix (verified by reverting it) and pass with it
  • Full com.arcadedb.index.fulltext.**, com.arcadedb.index.RebuildIndex*, com.arcadedb.query.sql.parser.RebuildIndexStatement*, and com.arcadedb.function.sql.fulltext.** suites: 245 tests, 0 failures
  • Full com.arcadedb.schema.** suite: 612 tests, 0 failures

🤖 Generated with Claude Code

…SPATIAL index

RebuildIndexStatement.buildIndex() drops and recreates a TypeIndex without
carrying its own name through the new TypeIndexBuilder, so create() never
sets metadata.typeIndexName and LocalDocumentType.addIndexInternal falls
back to the auto-derived "typeName[properties]" form. A plain LSM_TREE
rebuild happened to keep its name because its metadata object is reused
as-is, but FULL_TEXT and GEOSPATIAL reconstruct their metadata from the
index's persisted JSON to recover analyzer/precision settings, and
typeIndexName isn't part of that JSON - so the name silently reverts and
every name-based lookup (SEARCH_INDEX has no other way to reference an
index) breaks after a rebuild.

Fix: pass withIndexName(idx.getName()) into the rebuild so the name
survives regardless of which metadata path the index type takes.

The other two symptoms reported in #5791 (FULL_TEXT build over existing
data indexing nothing matchable, and an NPE on prefix queries against a
churned index) do not reproduce on current main: a stress test replaying
the reporter's SCD2-style churn pattern (thousands of staggered inserts,
growing updates that force placeholder relocations, and deletes, crossing
the 5,000-record build-batch boundary) shows every pre-existing row
matchable after CREATE INDEX ... FULL_TEXT, and prefix/wildcard queries
against the same churned index complete without error - already covered by
prior fixes (#4732's build-through-put() rewrite and #5635's IndexCursor
contract change that makes next() never return null).

Regression tests: RebuildIndexPreservesNameTest (plain/FULL_TEXT/GEOSPATIAL
index rebuild keeps its name) and FullTextBuildOverChurnedDataTest (the
full churn-then-build-then-rebuild-then-prefix-query scenario from the
report).
@mergify

mergify Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@codacy-production

codacy-production Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 0 complexity

Metric Results
Complexity 0

View in Codacy

🟢 Coverage 75.00% diff coverage · -6.37% coverage variation

Metric Results
Coverage variation ✅ -6.37% coverage variation
Diff coverage ✅ 75.00% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (ea4f6af) 152855 117429 76.82%
Head commit (a95cb1e) 185202 (+32347) 130482 (+13053) 70.45% (-6.37%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#5925) 4 3 75.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@claude

claude Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review

I traced the fix through the full metadata path (RebuildIndexStatement.buildIndex() → TypeIndexBuilder.create() → LocalDocumentType.addIndexInternal) and it holds up.

Correctness

  • TypeIndexBuilder.create() (line ~206) does if (indexName != null && !indexName.isEmpty()) metadata.typeIndexName = indexName; unconditionally at the top of create(), i.e. after .withMetadata(rebuildMetadata) has already been applied. That means the new .withIndexName(idx.getName()) call correctly overrides whatever typeIndexName the FULL_TEXT/GEOSPATIAL path's JSON-reconstructed metadata did or didn't carry - confirmed typeIndexName is never written by any toJSON() in index/lsm/*, so the JSON reconstruction really does drop it, matching the PR description.
  • Verified TypeGeoIndexBuilder and TypeFullTextIndexBuilder don't override create(), so both inherit the name-preservation line - the fix genuinely covers all three tested index kinds through one code path rather than needing type-specific handling.
  • Good catch on why the all/* sweep path doesn't need the same fix: REBUILD INDEX * only targets bucket-level sub-indexes (idx.isAutomatic() && !(idx instanceof TypeIndex)), which go through buildBucketIndex and reuse the existing TypeIndex wrapper rather than dropping/recreating it. Only the named-index path that rebuilds a TypeIndex directly hits the bug. Worth calling that out explicitly in the PR description or a code comment somewhere, since it's a reasonable question a reviewer will ask ("why not fix the bucket-index branch too?").
  • For unnamed/auto-derived indexes, idx.getName() already equals the auto-derived typeName[properties] form, so the new unconditional withIndexName() call is a no-op there - no behavior change for the common case.

Test coverage

  • RebuildIndexPreservesNameTest cleanly covers the three index kinds (LSM_TREE, FULL_TEXT, GEOSPATIAL) that take different metadata-reconstruction paths, which is exactly the right axis to test on given the root cause.
  • FullTextBuildOverChurnedDataTest is a solid regression/reproduction test for the two non-reproducing symptoms from BUG: FULL_TEXT index build over existing data still indexes nothing matchable on 26.7.2 (follow-up to #4732); prefix queries on such an index throw NPE #5791, and correctly @Tag("slow")'d per the project convention given ~6800 rows across multiple churn rounds.
  • Minor gap (not blocking): no test exercises REBUILD INDEX * on a named FULL_TEXT/GEOSPATIAL index to confirm the sweep path was never broken in the first place. Given the code-path analysis above it's provably unaffected, but a one-line test would make that assumption explicit and future-proof against someone later changing the all sweep to also go through buildTypeIndex.

Style / minor

  • The inline comment added at the fix site is appropriately scoped (explains the non-obvious why, references the issue) per the repo's comment guidance.
  • FullTextBuildOverChurnedDataTest.NEEDLE_CYR and friends use aligned-spacing field declarations consistent with the rest of the codebase.

Performance / security

No concerns. This is a schema-metadata bugfix with no new allocations on a hot path and no new dependencies.

Overall: a well-scoped, correctly-targeted fix with tests that match the actual root cause rather than just the symptom. Nice investigative work distinguishing the one reproducible symptom from the two that no longer apply on main.

…ngle-bucket types

Follow-up to the previous commit, prompted by a code review question this
PR's own automated review raised ("why doesn't the * sweep need the same
fix?"). Verifying that assumption with a test instead of taking it on faith
showed it was wrong: REBUILD INDEX * targets bucket sub-indexes rather than
the TypeIndex wrapper directly, but LocalSchema.dropIndex removes a
TypeIndex once it has no sub-index left - which is exactly what happens on
a single-bucket type (the common default), since its one sub-index is
always the last one. The freshly rebuilt sub-index then finds no existing
TypeIndex to reattach to, mints a new one, and hits the same auto-derived-
name fallback the previous commit fixed for the direct named-index rebuild
path.

BucketIndexBuilder.create() never carried a caller-supplied name onto the
metadata it hands to createBucketIndex(), unlike TypeIndexBuilder. Give it
the same carry-over, and have RebuildIndexStatement.buildIndex() capture
the owning TypeIndex's name (via IndexInternal.getTypeIndex()) before the
drop and pass it through withIndexName(...) on the bucket-index rebuild
branch too.

Extended RebuildIndexPreservesNameTest with a REBUILD INDEX * case over the
single-bucket FULL_TEXT/GEOSPATIAL indexes from the earlier tests, which
fails without this commit's fix.
@claude

claude Bot commented Aug 7, 2026

Copy link
Copy Markdown

placeholder-test

@claude

claude Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review

I traced the fix through the full call chain (RebuildIndexStatement.buildIndex -> TypeIndexBuilder/BucketIndexBuilder.create() -> LocalSchema.createBucketIndex -> LocalDocumentType.addIndexInternal) and it holds up. Summary of what I verified:

Root cause and fix are correctly diagnosed. LocalSchema.dropIndexInternal really does remove the TypeIndex wrapper once its last bucket sub-index is dropped (confirmed at LocalSchema.java:786-789), which is exactly the single-bucket-type trap the second commit describes. addIndexInternal only reads index.getMetadata().typeIndexName when it has to mint a new wrapper (propIndex == null branch, LocalDocumentType.java:1294-1306); when the wrapper survives (multi-bucket case), the passed-through name is simply unused, so the fix is a no-op there rather than a risk of unwanted renames. I checked this by hand for both the "last sub-index" and "not-last sub-index" cases and the logic is sound either way.

ownerTypeIndex capture is correctly ordered. It is read via ((IndexInternal) idx).getTypeIndex() before dropIndex() runs (RebuildIndexStatement.java:358 vs :395), so it always reflects the live wrapper name pre-drop, regardless of iteration order across the REBUILD INDEX * bucket sweep.

No aliasing hazard from the new metadata.typeIndexName mutation. For FULL_TEXT/GEOSPATIAL, rebuildMetadata is a freshly constructed object, so mutating it is safe. For the plain-index path, ((IndexInternal) idx).getMetadata() does return a live reference to the old index metadata object (confirmed in LSMTreeIndex.getMetadata()), but that reuse pattern already existed before this PR (per the PR description: "its metadata object is reused as-is") - the new .typeIndexName = indexName write onto it is harmless since the old index is already dropped by that point.

Persistence path is unaffected. LocalDocumentType.toJSON() derives whether a name is "custom" by comparing i.getName() against the recomputed auto-derived form (LocalDocumentType.java:1797-1798), not by checking whether metadata.typeIndexName is set, so setting typeIndexName unconditionally (even to an auto-derived value, for previously-unnamed indexes) does not cause schema.json to start persisting spurious typeIndexName entries.

Minor, non-blocking observations

  1. DatabaseChecker (integrity-check auto-fix path) has the same latent defect and is not touched here. DatabaseChecker.java:255-260 drops and rebuilds a corrupted bucket index via buildBucketIndex(...).create() without withIndexName(...), so a single-bucket-type explicitly-named index would silently revert to its auto-derived name after a DatabaseChecker fix, same as the bug fixed here for REBUILD INDEX. It also does not reconstruct FullTextIndexMetadata/GeoIndexMetadata from JSON the way RebuildIndexStatement now does, so a FULL_TEXT/GEOSPATIAL index repaired via DatabaseChecker would additionally lose its analyzer/precision settings - a pre-existing, separate issue. Worth a follow-up ticket if in scope; not a reason to block this PR, which is correctly scoped to the reported issue.

  2. Test coverage gap (not a bug): there is no regression test asserting the no-regression case - REBUILD INDEX * over a multi-bucket type keeping its TypeIndex name (the pre-existing, already-safe path). The existing tests cover the single-bucket case thoroughly; a multi-bucket case would round out the coverage and guard against a future change accidentally breaking the "wrapper survives, name unused" branch.

  3. Style: comments are long relative to typical code (though consistent with this file existing very-detailed comment style), and the fix nicely mirrors the existing TypeIndexBuilder#create() pattern rather than inventing a new one, per the project guidance to reuse existing components.

Test coverage
Good - three index kinds (LSM_TREE, FULL_TEXT, GEOSPATIAL) times two rebuild paths (named + *), plus a realistic churn-based regression test for the two previously-reported-but-non-reproducing symptoms, correctly tagged @tag("slow") per the project convention. I did not execute the Maven build in this environment, but the logic checks out against the current main sources.

No blocking issues found.

…DEX *

Round out RebuildIndexPreservesNameTest per the second code-review round:
on a multi-bucket type, the TypeIndex wrapper always has a surviving
sub-index while another one is being rebuilt, so it is never dropped and
addIndexInternal reattaches to it directly - the withIndexName(...) this
PR threads through is unused on that path. Passes as-is, confirming the
review's own analysis that the multi-bucket path was never at risk; locks
it in against a future change to the sweep.

Also filed #5934 for a related, out-of-scope defect the same review round
surfaced: DatabaseChecker's CHECK DATABASE FIX path rebuilds a corrupted
bucket index via buildBucketIndex(...).create() with neither
withIndexName(...) nor any metadata at all, so it can both rename an index
and drop FULL_TEXT/GEOSPATIAL settings entirely. Left for a separate PR
since it is a different command with a wider blast radius than this one.
@lvca

lvca commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

Addressed the second review round:

  • Multi-bucket coverage gap: added rebuildAllKeepsNameOnMultiBucketFullTextIndex, confirming the reviewer's own analysis - on a multi-bucket type the TypeIndex wrapper always survives (another sub-index keeps it alive), so the withIndexName(...) this PR adds is a no-op there. Passes as-is.
  • DatabaseChecker latent defect: confirmed by inspection (same drop-then-buildBucketIndex()-without-name-or-metadata shape, plus it drops FULL_TEXT/GEOSPATIAL settings entirely since it passes no metadata at all). Filed as CHECK DATABASE FIX loses index name and type-specific metadata when rebuilding a corrupted bucket index #5934 rather than fixed here - it's a different command (CHECK DATABASE FIX) with a wider blast radius than this PR's scope.
  • Style note: no action, per the reviewer's own read that the comment density matches this file's existing style.

@claude

claude Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review

I traced the fix through the full metadata-propagation chain and it holds up.

Mechanism verified correct. RebuildIndexStatement.buildIndex() now passes withIndexName(...) into both the TypeIndex rebuild path and the bucket-sub-index rebuild path. For the latter, BucketIndexBuilder.create() was missing the step TypeIndexBuilder.create() already had (line ~207): copying indexName onto metadata.typeIndexName. I confirmed the whole pipeline end-to-end:

  • BucketIndexBuilder.create() sets metadata.typeIndexName
  • that metadata flows unchanged into LocalSchema.createBucketIndex(...), which copies it onto index.getMetadata().typeIndexName (LocalSchema.java:2503-2504)
  • LocalDocumentType.addIndexInternal reads that field only when it has to mint a new TypeIndex wrapper (propIndex == null), i.e. exactly the single-bucket-type case this PR targets, where dropping the last sub-index also drops the wrapper (LocalSchema.dropIndex)
  • when the wrapper survives (multi-bucket case), the field is simply unused - correctly covered by the rebuildAllKeepsNameOnMultiBucketFullTextIndex test

The ownerTypeIndex capture happens before the destructive dropIndex call, which is necessary since getTypeIndex() on the sub-index would return null/stale after the wrapper is torn down. Good catch, and it's a real bug independent from the primary typeIndexRebuild fix - the PR is right that REBUILD INDEX * needed the same treatment as a direct named rebuild for the (very common) single-bucket-type case.

Minor observations, none blocking:

  • In BucketIndexBuilder.create(), metadata.typeIndexName = indexName mutates the metadata object of the index that's about to be dropped for the plain LSM_TREE case (since indexMetadata = ((IndexInternal) idx).getMetadata() reuses the live object rather than copying it). By the time this runs, dropIndex() has already executed, so it's a no-op in practice on an already-discarded object - not a bug, just worth flagging since it's easy to misread as mutating live index state.
  • The defensive if (metadata == null) metadata = new IndexMetadata(...) branch in BucketIndexBuilder is currently unreachable from any caller (only RebuildIndexStatement calls withIndexName on this builder, and it always also calls withMetadata), but it's cheap, correct, and guards future callers - fine to keep.
  • all (REBUILD INDEX *) still deliberately excludes TypeIndex itself from the target list; the added comment explaining why that's still safe after this fix is helpful and accurate.

Test coverage is solid: the four cases in RebuildIndexPreservesNameTest (plain/FULL_TEXT/GEOSPATIAL named rebuild, * sweep on single-bucket types, and the multi-bucket "wrapper survives" case) map precisely onto the branches touched by the fix. FullTextBuildOverChurnedDataTest is appropriately @Tag("slow") per the repo's testing convention and does a good job reproducing the reporter's exact scenario (age/churn rather than volume) to substantiate the PR's claim that the other two reported symptoms don't reproduce on main. No stray System.out, no Claude authorship in the added files, license headers present.

Not verified in this review: I wasn't able to run mvn compile/tests in this sandboxed session (Maven invocations require interactive approval that wasn't available here), so this is a static-analysis review only. The PR description states mvn -pl engine install -DskipTests and the full relevant suites (245 + 612 tests) pass locally - I'd lean on that plus CI rather than re-deriving it, but flagging so it's clear I didn't independently execute anything.

Nice write-up in the PR description distinguishing "fixed" from "does not reproduce" with concrete reasoning for each - that's the right way to close out a multi-symptom report.

@codecov

codecov Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 25.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.09%. Comparing base (ea4f6af) to head (a95cb1e).
⚠️ Report is 6 commits behind head on main.

Files with missing lines Patch % Lines
...n/java/com/arcadedb/schema/BucketIndexBuilder.java 25.00% 1 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5925      +/-   ##
==========================================
+ Coverage   68.03%   68.09%   +0.06%     
==========================================
  Files        1797     1797              
  Lines      152855   152859       +4     
  Branches    32397    32399       +2     
==========================================
+ Hits       103999   104095      +96     
+ Misses      35466    35376      -90     
+ Partials    13390    13388       -2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@lvca lvca self-assigned this Aug 7, 2026
@lvca lvca added this to the 26.9.1 milestone Aug 7, 2026
@lvca
lvca merged commit 9930864 into main Aug 7, 2026
60 of 73 checks passed
@lvca
lvca deleted the issue-5791-fulltext-build-existing branch August 7, 2026 20:51
lvca added a commit that referenced this pull request Aug 10, 2026
* fix: batch fixes for #5934, #5937, #5958

- #5934: CHECK DATABASE FIX's index-rebuild path dropped and rebuilt a
  corrupted bucket sub-index with no withIndexName()/withMetadata(),
  the same defect #5925 fixed for REBUILD INDEX. A single-bucket type
  lost its explicitly-named TypeIndex wrapper, and a FULL_TEXT/
  GEOSPATIAL index lost its analyzer/precision settings, every time
  the check repaired one of their bucket sub-indexes.

- #5937: the plain (unshaded) arcadedb-gremlin Maven coordinate
  crashed with a raw ExceptionInInitializerError/InvalidClassException
  the first time it ran a textual Gremlin query, because a downstream
  consumer's classpath resolves only the engine's ANTLR 4.13.2
  runtime while TinkerPop's precompiled grammar needs 4.9.1's ATN
  format. ArcadeGremlin now recognizes that specific failure shape and
  raises an actionable CommandExecutionException pointing at the
  arcadedb-gremlin:shaded classifier, instead of leaking ANTLR
  internals. Textual Gremlin still requires the shaded classifier;
  this only makes the failure diagnosable.

- #5958: Cypher25AntlrParser attached its CypherErrorListener to the
  parser but never to the lexer, unlike SQLAntlrParser after #5951/
  #5957. Fixed for consistency and to guard future grammar changes;
  the regression test pins that lexically malformed input still
  raises CommandParsingException.

* fix: address code review on #6031

- ArcadeGremlin.translateAntlrAtnMismatch: Codacy flagged the reference-identity
  cycle guard (next == c) as a raw == comparison on Throwable. Switched to
  Objects.equals(), which is null-safe and behaviorally identical since
  Throwable does not override equals().
- Cypher25AntlrParser.parseQuery: reuse a single CypherErrorListener instance for
  both lexer and parser, matching SQLAntlrParser's pattern (minor stylistic note
  from review; CypherErrorListener is stateless so this is behavior-preserving).

* fix: address code review on #6031 (file-locking coverage)

DatabaseChecker's index-rebuild loop dropped and rebuilt a corrupted bucket
sub-index without holding the file lock RebuildIndexStatement.buildIndex()
takes for the same drop+rebuild sequence. Wrap both steps in
executeLockingFiles(idx.getFileIds(), ...), matching the sibling
implementation, so a concurrent writer can't observe the index gone-then-back
with entries missing and the commit-time lock-coverage check can't throw on
the newly-created file.

* fix: address code review on #6031 (deduplicate FULL_TEXT/GEOSPATIAL rebuild metadata)

DatabaseChecker's new auto-fix rebuild path and RebuildIndexStatement.buildIndex()
now had the same ~10-line FULL_TEXT/GEOSPATIAL metadata-reconstruction block
copy-pasted verbatim. Factored into IndexMetadata.reconstructForRebuild(idx,
typeName, propertyNames), a static helper both call, so a future third case or a
bugfix to this logic only needs to be applied once.

* fix: address code review on #6031 (retry the index-rebuild lock)

DatabaseChecker's drop+rebuild lock (added to mirror RebuildIndexStatement's
file-locking coverage) had no retry loop for lock contention, unlike
RebuildIndexStatement.buildIndex(), which retries NeedRetryException /
LockTimeoutException up to MAX_ATTEMPTS with backoff. Widening the locked
section to cover both the drop and the create - the whole point of that fix -
widens the window a concurrent writer can contend on, so add the same bounded
retry. Unlike RebuildIndexStatement, which silently returns once attempts are
exhausted, this rethrows: CHECK DATABASE FIX should fail loudly rather than
quietly leave an index unrepaired while still reporting success.

* fix: address code review on #6031 (document auto-mode fail-fast)

Add the one-line comment code review suggested at the 'auto' -> java engine
try/catch in ArcadeGremlin.executeStatement(boolean): the ATN-mismatch
CommandExecutionException is unchecked, so it propagates past the
catch (ScriptException e) used for the auto -> Groovy fallback, meaning 'auto'
mode fails fast on this classpath defect instead of silently falling back to
the insecure Groovy engine. Intentional, now documented at the call site.

* docs: address code review on #6031 (document pre-existing retry race)

Review round 5 correctly noted that retrying the whole drop+create body can
re-enter with the drop already committed if create()'s bucket scan raises
NeedRetryException, restarting from a different state than a clean retry
assumes. Confirmed this exact shape already exists, unchanged, in
RebuildIndexStatement.buildIndex() - not introduced by this PR, just given a
second call site and (via the rethrow-on-exhaustion choice from the prior
review round) more likely to surface if it happens. A proper fix (skip the
drop on retry, or scope retry to lock acquisition only) needs to touch both
call sites together, which is out of scope for this batch fix; documented the
known race at the call site instead, and trimmed the now-lengthy comment block
per the review's other minor note.

* fix: address code review on #6031 (isolate lock-contention failure per index)

DatabaseChecker's retry loop previously rethrew once LOCK_MAX_ATTEMPTS was
exhausted, unwinding out of check() entirely. Since CheckDatabaseStatement has
no catch around checker.check(), that aborted the WHOLE CHECK DATABASE FIX
run - discarding every corrupted record already found and fixed, every index
already rebuilt earlier in the affectedIndexes iteration, skipping every index
still to come, and skipping the compress step - all because one index stayed
lock-contended on a busy database (exactly the scenario the retry was added
to survive).

Isolate the failure to that one index instead: on exhausted retries, remove
it from the reported rebuiltIndexes set (so the result doesn't claim a
rebuild that didn't happen) and record a warning via addWarning(), matching
this class's existing "reported, never silent" convention, then continue
rebuilding the rest of affectedIndexes. An InterruptedException during the
backoff sleep still aborts immediately, since that is a stop request rather
than contention to ride out.

* fix: address code review on #6031 (comment accuracy + plain-index test)

- Refine the "known pre-existing race" comment on DatabaseChecker's retry
  loop: dropIndex() itself does not throw on retry (LocalSchema.dropIndexInternal
  no-ops once the name is gone); the actual risk is create() running a second
  time after a prior attempt's drop already committed, not resuming from where
  create() failed. Also note that capturing rebuildMetadata/ownerTypeIndex once
  before the loop (vs RebuildIndexStatement recomputing them per-attempt) is a
  hoist, not a behavior change, since both read idx before any attempt's drop.
- Add fixPreservesExplicitNameOnPlainIndex to CheckDatabaseFixPreservesIndexMetadataTest,
  covering the plain (non-FULL_TEXT/GEOSPATIAL) TypeIndex-name-preservation case
  for CHECK DATABASE FIX's rebuild path, matching RebuildIndexPreservesNameTest's
  equivalent coverage for REBUILD INDEX.

* fix: address code review on #6031 (recompute rebuild metadata per retry attempt)

Real bug caught by review: rebuildMetadata was computed once, before the retry
loop, so a retried FULL_TEXT rebuild reused the same FullTextIndexMetadata
instance whose BM25 corpus counters (totalDocs/sumDocLength) had already been
partially incremented by the failed attempt's create() call - addDocument()
mutates the instance in place and is not reversed on rollback. Attempt N+1
then indexed every record again on top of attempt N's partial counts,
inflating the corpus stats and skewing BM25 relevance scoring on any FULL_TEXT
index whose rebuild needed more than one attempt. GEOSPATIAL was unaffected
(GeoIndexMetadata has no equivalent mutable accumulator).

Move IndexMetadata.reconstructForRebuild(...) inside the retry loop so each
attempt gets a fresh, zeroed metadata instance, matching
RebuildIndexStatement.buildIndex()'s per-attempt recomputation. ownerTypeIndex
stays hoisted: it is a plain name read off idx, unaffected by attempt count.

* docs: address code review on #6031 (explain hoisted retry-loop locals)

Comment-only change: document why bucketName/indexType/unique/propNames/
typeName/pageSize/nullStrategy are safe to read once before the retry loop
(plain idempotent reads off pre-drop idx/schema state, no mutable
accumulator), unlike rebuildMetadata just below them, which for FULL_TEXT
wraps a live BM25 counter and is recomputed per attempt for exactly that
reason.

* fix: address code review on #6031 (do not blame lock contention unconditionally)

The retry-exhaustion warning unconditionally said "due to lock contention",
but NeedRetryException reaching that branch can also come from the documented
pre-existing race (a later attempt's create() failing after an earlier
attempt's drop already committed) - in which case the index may be genuinely
missing, not merely un-rebuilt, and "lock contention" is the wrong diagnosis
to hand an operator. Reworded to state the rebuild did not finish and the
index may be missing, point at re-running CHECK DATABASE FIX, and give a
SELECT FROM schema:indexes query to verify - without claiming a specific root
cause the code cannot actually distinguish from lastRetryFailure alone.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant